const { query } = require('../../helper/db');
const { door, ok } = require('../../helper/util');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 好友
 * @api {GET} api/friend/list 好友列表
 * @apiName api/friend/list
 * @apiExample {js} axios 例子:
 *  axios.get('http://39.105.38.34:8080/api/friend/list', {
 *    params: {
 *      size: 10,
 *      page: 1,
 *      status: 2,
 *    }
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {Number} status 与好友的状态 1 申请中, 2 已为好友, 3 已删除好友
 * @apiParam {Number} [page=1] 分页的页数
 * @apiParam {Number} [size=10] 每页的条数
 * @apiSuccess (请求成功) {Array} friendlist 好友列表
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var params = ctx.query;
  var user = await door(token);

  var sql = ['select * from relation_ship where 1 = 1'];
  var values = [];

  sql.push('and userid = ?');
  values.push(user.id);

  if (params.status) {
    sql.push('and status = ?');
    values.push(Number(params.status));
  }

  if (page && size) {
    var page = params.page ? params.page : 1;
    var size = params.size ? params.size : 10;
    var end = page * size;

    sql.push('order by id desc limit ?, ?');
    values.push(end - size);
    values.push(end);
  }

  var friendlist = await query(sql.join(' '), values);
  var userids = friendlist.map(friend => friend.friendID);
  var userlist = userids.length ? await query('select * from user where id in (?)', [userids]) : [];

  friendlist.forEach(friend => {
    userlist.forEach(user => {
      if (friend.friendID === user.id) {
        friend.nickname = user.nickname;
        friend.email = user.email;
        friend.age = user.age;
        friend.avatar = user.avatar;
        // friend.status = user.status;
        friend.username = user.username;
        friend.userid = user.id;
      }
    });
  });

  ctx.body = ok({ friendlist });
}